package com.gusti.admincasa.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.gusti.admincasa.dao.ITimeRegisterDao;
import com.gusti.admincasa.model.TimeRegister;
import com.gusti.admincasa.model.User;
import com.gusti.admincasa.util.Debug;

/**
 * 
 * @author gusti
 *
 */
@Repository
public class TimeRegisterDao extends ProjectDao<TimeRegister> implements ITimeRegisterDao {

	public TimeRegister findTimeRegister( String uuid ) {
		TimeRegister timeRegister = new TimeRegister();

		Query query = null;
		try {
			query = em.createQuery( "FROM TimeRegister as tr WHERE tr.uuid = :uuid" );
			query.setParameter( "uuid", uuid );
			timeRegister = (TimeRegister)query.getSingleResult();
		} catch ( Exception e ) {
			Debug.error( e );
		}

		return timeRegister;
	}

	public TimeRegister findLastTimeRegister( User user ) {
		TimeRegister timeRegister = new TimeRegister();

		Query query = null;
		try {
			query = em.createQuery( "FROM TimeRegister as tr WHERE tr.id = ( SELECT MAX(id) FROM TimeRegister WHERE user = :user )" );
			query.setParameter( "user", user );
			timeRegister = (TimeRegister)query.getSingleResult();
		} catch ( Exception e ) {
			Debug.error( e );
		}

		return timeRegister;
	}

	@SuppressWarnings("unchecked")
	public List<TimeRegister> findTimeRegisters( User user ) {
		List<TimeRegister> timeRegister = new ArrayList<TimeRegister>();
		
		Query query = null;
		try {
			query = em.createQuery( "FROM TimeRegister as tr WHERE tr.user = :user ORDER BY tr.id DESC" );
			query.setParameter( "user", user );
			query.setMaxResults( 10 );
			timeRegister = (List<TimeRegister>)query.getResultList();
		} catch ( Exception e ) {
			Debug.error( e );
		}
		
		return timeRegister;
	}

}
